package net.expectx.pay.gateway.rpc.service.impl;

import net.expectx.common.single.base.BaseResult;
import net.expectx.pay.gateway.dao.bean.ProductOrderHeader;
import net.expectx.pay.gateway.dao.bean.ProductOrderHeaderExample;
import net.expectx.pay.gateway.dao.bean.ProductOrderPaymentRecord;
import net.expectx.pay.gateway.dao.mapper.ProductOrderHeaderMapper;
import net.expectx.pay.gateway.dao.mapper.ProductOrderPaymentRecordMapper;
import net.expectx.pay.gateway.rpc.api.ProductOrderHeaderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ProductOrderHeaderService实现
 * @author lijian
 * @date 2019/8/24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProductOrderHeaderServiceImpl extends BaseServiceImpl<ProductOrderHeader, ProductOrderHeaderExample> implements ProductOrderHeaderService {

    private static final Logger LOGGER = Logger.getLogger(ProductOrderHeaderServiceImpl.class);

    @Autowired
    ProductOrderHeaderMapper productOrderHeaderMapper;
    @Autowired
    ProductOrderPaymentRecordMapper productOrderPaymentRecordMapper;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    public BaseResult createOrder(Map<String,String> params ){
        String merchantNo=params.get("merchantNo");
        String applicationNo=params.get("applicationNo");
        String merchantOrderId=params.get("merchantOrderId");
        String orderName=params.get("orderName");
        String orderDesc=params.get("orderDesc");
        String orderDate=params.get("orderDate");
        String currencyUom=params.get("currencyUom");
        String tradeAmount=params.get("tradeAmount");
        /**
         * 创建订单
         */
        ProductOrderHeader productOrderHeader = new ProductOrderHeader();
        productOrderHeader.setMerchantNo(merchantNo);
        productOrderHeader.setAgentNo(applicationNo);
        productOrderHeader.setMerchantOrderId(merchantOrderId);
        productOrderHeader.setOrderName(orderName);
        productOrderHeader.setOrderDesc(orderDesc);
        productOrderHeader.setOrderDate(Long.valueOf(orderDate));
        productOrderHeader.setCurrencyUom(currencyUom);
        productOrderHeader.setGrandTotal(new BigDecimal(tradeAmount));
        productOrderHeader.setOrderType("1");
        if (params.containsKey("notifyUrl")){
            String notifyUrl=params.get("notifyUrl");
            productOrderHeader.setNotifyUrl(notifyUrl);
        }
        if (params.containsKey("channel")){
            String channelId=params.get("channel");
            productOrderHeader.setChannelId(Long.valueOf(channelId));
        }
        BaseResult baseResult = createOrder(productOrderHeader);
        return baseResult;
    }
    @Override
    public BaseResult createOrder(ProductOrderHeader productOrderHeader) {
        ProductOrderHeader orderHeader=null;
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            ProductOrderHeaderExample orderHeaderExample=new ProductOrderHeaderExample();
            ProductOrderHeaderExample.Criteria criteria=orderHeaderExample.createCriteria();
            criteria.andMerchantNoEqualTo(productOrderHeader.getMerchantNo());
            criteria.andMerchantOrderIdEqualTo(productOrderHeader.getMerchantOrderId());
            List<ProductOrderHeader> orderHeaders=productOrderHeaderMapper.selectByExample(orderHeaderExample);
            if (orderHeaders.isEmpty()){
                SimpleDateFormat simpleDateFormat;
                simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                String str = simpleDateFormat.format(date);
                Random random = new Random();
                int ranMum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
                String orderId = "EX"+ranMum + str;
                ranMum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
                orderId = orderId+ranMum;
                productOrderHeader.setOrderId(orderId);
                productOrderHeader.setGmtModified(System.currentTimeMillis());
                productOrderHeader.setGmtCreate(System.currentTimeMillis());
                productOrderHeader.setOrderStatus("0");
                int i=productOrderHeaderMapper.insertSelective(productOrderHeader);
                if (i == 0) {
                    throw new Exception();
                }else{
                    ProductOrderPaymentRecord productOrderPaymentRecord=new ProductOrderPaymentRecord();
                    productOrderPaymentRecord.setOrderId(orderId);
                    productOrderPaymentRecord.setGmtModified(System.currentTimeMillis());
                    productOrderPaymentRecord.setGmtCreate(System.currentTimeMillis());
                    productOrderPaymentRecord.setPayStatus("0");
                    productOrderPaymentRecord.setTotalFee(new BigDecimal(0));
                    productOrderPaymentRecord.setRecordId(UUID.randomUUID().toString().replace("-",""));
                    productOrderPaymentRecordMapper.insertSelective(productOrderPaymentRecord);
                    orderHeader=productOrderHeader;
                }
            }else{
                orderHeader=orderHeaders.get(0);
            }
            transactionManager.commit(status);
            return new BaseResult(true, "订单创建成功", orderHeader);
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback(status);
            return new BaseResult(false, "系统错误:" + e.getLocalizedMessage(), null);
        }
    }

}
